package org.setamv.springcloud.hystrix.raw.command.strategy;

import com.netflix.config.ConfigurationManager;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandProperties;

public class SemaphoreStrategyCommandTest {

    public static void main(String[] args) throws Exception {
        // 设置隔离策略为semaphore类型（默认为thread类型）
        ConfigurationManager.getConfigInstance().setProperty(
                "hystrix.command.default.execution.isolation.strategy",
                HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE);
        // 设置semaphore类型的最大并发数为3
        ConfigurationManager.getConfigInstance().setProperty(
                "hystrix.command.default.execution.isolation.semaphore.maxConcurrentRequests",
                3);

        for (int i = 0; i < 5; i++) {
            SemaphoreStrategyCommand command = new SemaphoreStrategyCommand(i);
            // 因为semaphore方式的隔离策略是使用当前线程执行明林，这个区别与thread类型，thread类型会将命令放到线程池中执行
            // 所以如果要模拟并发，必须手动创建线程执行
            new Thread(() -> {
                command.queue();
            }).start();
        }
        Thread.sleep(5000);

    }

    public static class SemaphoreStrategyCommand extends HystrixCommand<String> {

        private int index;
        public SemaphoreStrategyCommand(int index) {
            super(HystrixCommandGroupKey.Factory.asKey("testGroup"), 1000);
            this.index = index;
        }

        @Override
        protected String run() throws Exception {
            System.out.println("run " + index);
            return "run " + index;
        }

        @Override
        protected String getFallback() {
            System.out.println("fallback " + index);
            return "fallback " + index;
        }
    }
}
